<!--
 * @Description: 扫二维码加入群
 * @Author: Kerwin
 * @Date: 2025-04-08 17:19:58
 * @LastEditTime: 2025-04-14 16:27:16
 * @LastEditors:  Please set LastEditors
-->

<template>
    <view class="box">
        <view class="headerIcon">
            <view class="avatar">
                <u-avatar v-for="(item, index) in userList" mode="square" :src="getImgFullPath(item.avatar)"></u-avatar>
            </view>
        </view>
        <view class="title">{{ groupInfo.name }}({{ userList.length }})</view>
        <u-button class="footer" type="success" @click="joinGroup">加入群聊</u-button>
    </view>
</template>

<script setup lang="ts">
import { onLoad, onShow } from '@dcloudio/uni-app'
import { reactive, ref, computed, onBeforeMount, watch } from 'vue'
//api
import { socialApi, userApi } from '@/api'
import { storeToRefs } from 'pinia'
import RongIMLib from '@/packageD/common/rongCloud/im_init';
//工具
import { useUserStore, useConfigStore, useChatStore } from '@/store'
import { route } from '@/utils/common';
//默认头像
import { UPLOADURL, RY_AVATAR } from '@/common/config'
import { getImgFullPath } from '@/utils/index'

//#region ***************************** 初始出数据 **************************/
const userStore = useUserStore()
const { userInfo } = storeToRefs(userStore)
const ryStore = useChatStore()
const groupInfo = ref<any>({
    groupCode: '',
    cid: ''
})
const userList = ref<any>([])
const userId = ref(userInfo.value?.id)
//#region ***************************** 处理初始出数据 **************************/
//1.需要先判断是否登录过，有没有账号，有就这个页面，没有就跳转到登录页面
onShow((option) => {
    console.log(option, '参数');

})
onLoad(async (option) => {
    console.log(option, '参数');
 
    if (!userStore.checkLoginState({ routeType: 'redirectTo', qrCode:option })) {
        return
    } else {
        infoAndRongYunToken()
        initRongCloud()
        getRongCloudToken()
    }
    groupInfo.value.groupCode = option?.groupCode
    groupInfo.value.cid = option?.cid
    //如果没有创建融云用户则创建
    await getUserDetailInfo()
    await circleUserList()
    await getCircleInfo()
    //如果当前用户id 存在在群聊中，则直接跳转
    if (userList.value.find((e: { userId: any }) => e.userId == userId.value)) {
        console.log('当前用户id 存在在群聊中，则直接跳转', groupInfo.value);
        toChat(groupInfo.value)
    }

})


//创建融云用户
const infoAndRongYunToken = async() =>{
    const { code, data } = await socialApi.infoAndRongYunToken({
        id: userId.value,
        userId: userId.value,
        detail: true
    })
    console.log('融云创建用户成功', data);
}
const initRongCloud = () => {
    const { Events } = RongIMLib
    RongIMLib.addEventListener(Events.CONNECTING, () => {
        console.log('正在链接服务器')
    })
    RongIMLib.addEventListener(Events.CONNECTED, () => {
        console.log('已经链接到服务器')
        const includeMuted = false
        const conversationTypes = [
            RongIMLib.ConversationType.PRIVATE,
            RongIMLib.ConversationType.GROUP
        ]
        RongIMLib.getTotalUnreadCount(includeMuted, conversationTypes)
            .then((res) => {
                if (res.code === 0) {
                    console.log('未读消息', res.data)
                } else {
                    console.log(res.code, res.msg)
                }
            })
            .catch((error) => {
                console.log(error)
            })
        RongIMLib.addEventListener(Events.MESSAGES, (evt) => {
            const { messages } = evt
            console.log('listener==>', evt)
            if (messages && messages.length > 0) {
                messages.forEach((message) => {
                    ryStore.setMessage(message, 'add')
                })
            }
        })
        RongIMLib.addEventListener(Events.EXPANSION, (evt) => {
            console.log('扩展信息：', evt)
            const { updatedExpansion, deletedExpansion } = evt;
            console.log('拓展信息更新：', updatedExpansion);
            console.log('拓展信息删除：', deletedExpansion);
        })
        RongIMLib.addEventListener(Events.CONVERSATION, (evt) => {
            console.log('会话监听：', evt);
            ryStore.updateConversation(evt)
        })
    })
}
// 获取用户融云token并建立链接
const getRongCloudToken = async () => {
    uni.showLoading({
        title: '加载中',
        mask: true
    })
    const { code, data } = await userApi.getRongCloudToken(userStore.userInfo?.id).finally(() => {
        uni.hideLoading()
    })
    if (code === 200) {
        const res = await ryStore.connect(data)
        if (res) {
            ryStore.updateMyUserProfile({
                name: userStore.userInfo?.nickname,
                portraitUri: getImgFullPath(userStore.userInfo?.avatar)?.replace(/^https:\/\/|^http:\/\//, "//")
            })
        }
    }
}


//获取到用户融云信息-- 并且创建一码人脉用户
async function getUserDetailInfo() {
    const { data } = await socialApi.userDetailInfo({
        id: userId.value,
        userId: userId.value,
        detail: true
    })
    console.log('融云创建用户成功', data);
}

//获取群聊具体信息
const getCircleInfo = async () => {
    const { data } = await socialApi.circleInfo({
        id: groupInfo.value.cid
        // detail: true
    })
    groupInfo.value = { ...groupInfo.value, ...data }
}

//获取群聊用户list
const circleUserList = async () => {
    const { data } = await socialApi.circleUserList({
        chatGroupId: groupInfo.value.gid,
        friendCircleId: groupInfo.value.cid,
        detail: true,
        // pageSize: 19
        noPaging: true
    })
    if (data && data.records.length > 0) {
        userList.value = data.records.map(
            (e: { userDetail: { avatar: string }; nickname: any; id: any }) => {

                if (!e.userDetail.avatar) {
                    e.userDetail.avatar = RY_AVATAR
                }
                return { ...e.userDetail, circle_nickname: e.nickname, fid: e.id }
            }
        )

        console.log(userList.value, '用户群聊');



    } else {
        userList.value = []
    }
}

//加入群聊
const joinGroup = async () => {
    console.log('加入群聊', groupInfo.value);

    let obj = {
        groupCode: groupInfo.value.groupCode,
        friendCircleId: groupInfo.value.cid,
        joinType: 6,
        shopId: groupInfo.value.shopId,
    }

    const { data, code } = await socialApi.joinChatGroupCity(obj)
    console.log(data, '加入群聊成功', groupInfo.value);
    if (code == 200) {

        toChat(groupInfo.value)
    }

}

//跳转到群聊详情
function toChat(item: {
    type?: any
    chatGroupId?: any
    id?: any
    targetId?: any,
    name?: any,
    portraitUri?: string,
    conversationType: RongIMLib.ConversationType.GROUP
}) {

    console.log('群聊===》', RongIMLib.ConversationType.GROUP, item);
    route({
        url: '/packageD/pages/chat/index',
        params: {
            targetId: item.id || item.targetId,
            userId: item.targetId,
            name: item.name,
            cid: item.id,
            type: item.type,
            conversationType: item.conversationType || RongIMLib.ConversationType.GROUP
        }
    })
}


</script>

<style lang="scss" scoped>
.box {
    display: flex;
    flex-direction: column;
    align-items: center;
}

.headerIcon {
    width: 190rpx;
    height: 190rpx;
    margin-top: 100rpx;
    margin-bottom: 50rpx;
    overflow: hidden;
    border: 4rpx solid #d4d0d0;
    background-color: #f6f6f6;
    display: flex;
    align-items: center;

    .avatar {
        margin: auto;
    }
}

.title {
    margin-bottom: 300rpx;
}

.footer {
    width: 300rpx;
}
</style>
